package com.spring.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spring.boot.entity.*;
//import com.spring.boot.service.UserService;
import com.spring.boot.service.SysMenuService;
import com.spring.boot.service.SysRoleMenuService;
import com.spring.boot.service.SysRoleService;
import com.spring.boot.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private SysUserRoleService userRoleService;
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysRoleMenuService roleMenuService;
    @Autowired
    private SysMenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo user = userService.getUserByUsername(username);
        if (user == null){
            throw new UsernameNotFoundException("用户不存在！");
        } else {
            List<SysUserRole> userRoles = userRoleService.getByUserId(user.getId());
            //        拿到权限集合
            List<GrantedAuthority> authorities = new ArrayList<>();
            for (SysUserRole userRole : userRoles) {
//                SysRole role = roleService.getById(userRole.getRoleId());
                List<SysRoleMenu> sysRoleMenus = roleMenuService.list(new QueryWrapper<SysRoleMenu>().eq("role_id", userRole.getRoleId()));
//                List<SysMenu> menuList = new ArrayList<>();
                for (SysRoleMenu roleMenu : sysRoleMenus) {
                    SysMenu menu = menuService.getById(roleMenu.getMenuId());
                    //        权限必须以“ROLE_”开头
                    authorities.add(new SimpleGrantedAuthority("ROLE_" + menu.getMenu()));
                }
            }
            return new User(user.getUsername(),user.getPassword(),authorities);
        }
    }
}
